package com.systemic.service.impl;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.template.Template;
import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.TemplateUtil;
import com.systemic.service.AuthService;
import com.systemic.service.EmailService;
import com.systemic.service.UserInfoService;
import com.systemic.dto.AuthUserDto;
import com.systemic.pojo.Email;
import com.systemic.pojo.User;
import com.systemic.pojo.UserInfo;
import com.systemic.service.UserService;
import com.systemic.utils.RedisUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.URISyntaxException;
import java.util.Collections;
import java.util.Date;

import static com.systemic.utils.FileUtils.copyImageToNginx;

/**
 * @ClassName: AuthServiceImpl
 * @Description:
 * @Author:
 * @CreateTime: 2023-12-27 14:28
 * @Version:
 **/
@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {

    @Value("${code.expiration}")
    private Long expiration;

    @Value("${image.avatarUrl}")
    private String avatarUrl;

    @Value("${image.avatar}")
    private String avatarPath;

    @Value("${image.bgUrl}")
    private String bgUrl;

    @Value("${image.background}")
    private String backgroundPath;

    private final String avatarName = "normal_avatar.png";
    private final String backGroundName = "normal_background.png";


    private final RedisUtils redisUtils;
    private final EmailService emailService;
    private final UserService userService;
    private final UserInfoService userInfoService;


    /**
     * 向指定邮箱发送验证码
     * @param email 邮箱号
     */
    @Override
    public void sendMailCode(String email) {

        // 获取发送邮箱验证码的HTML模板
        TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH));
        Template template = engine.getTemplate("emailTemplate.ftl");

        // 从redis缓存中尝试获取验证码
        Object code = redisUtils.get(email);
        if (code == null) {
            // 如果在缓存中未获取到验证码，则产生6位随机数，放入缓存中
            code = RandomUtil.randomNumbers(6);
            if (!redisUtils.set(email, code, expiration)) {
                throw new RuntimeException("后台缓存服务异常");
            }
        }
        // 发送验证码
        emailService.send(new Email(Collections.singletonList(email), "邮箱验证码", template.render(Dict.create().set("code", code))));

    }

    /**
     * 注册
     * @param authUserDto 检查验证码是否正确
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean register(AuthUserDto authUserDto) {
        String account = authUserDto.getEmail();
        // 通过email获取redis中的code
        Object value = redisUtils.get(account);
        if (value == null || !value.toString().equals(authUserDto.getCode())) {
            throw new RuntimeException("无效验证码");
        }
        System.out.println("当前注册用户"+ account +"验证成功");
        redisUtils.del(account);
        return true;
    }

    /**
     * 处理用户信息
     * @param user
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean information(User user) {
        UserInfo userInfo = new UserInfo();
        Date date = new Date();
        String account = user.getAccount();
        user.setGmtCreate(date);
        user.setGmtModified(date);
        try{
            System.out.println("正在尝试添加用户");
            userService.addUser(user);
        } catch (Exception e) {
           throw new RuntimeException("添加用户失败", e);
        }
        User newUser = userService.findByAccount(account);
        Integer uid = newUser.getUid();

        userInfo.setUid(uid);
        userInfo.setUname(account);
        userInfo.setEmail(account);
        userInfo.setGmtCreate(date);
        userInfo.setGmtModified(date);

        // TODO:新增默认头像和背景
        String avatarURL = copyImageToNginx(avatarName,avatarPath,avatarUrl);
        String BgURL = copyImageToNginx(backGroundName,backgroundPath,bgUrl);

        userInfo.setAvatar(avatarURL);
        userInfo.setBackground(BgURL);

        try{
            System.out.println("正在尝试添加用户信息");
            userInfoService.addUserInfo(userInfo);
        } catch (Exception e) {
            throw new RuntimeException("添加用户信息失败", e);
        }
        return true;
    }


}
